// App.tsx
import React from 'react';
import { useEffect, useState, useCallback } from 'react';
import { initView } from 'dingtalk-docs-cool-app';
import { Typography, Button, Collapse, Card, Tabs } from 'dingtalk-design-desktop';
import { getLocale } from './locales';
import './style.css';
import FinanceList from './FinanceList';
import FindDuplicate from './FindDuplicate';
import { useDocument, useDocumentEvents } from '../hooks/doc';
import { useRecord } from '../hooks/record';
import { useField } from '../hooks/field';

function App() {
  const [loading, setLoading] = useState<boolean>(false);
  
  const {
    locale, setLocale,
    documentInfo, loadDocumentInfo,
    sheets, loadSheets,
    activeSheet, loadActiveSheet,
    
  } = useDocument();

  // 使用 useRecord hook
  const {
     records,  setRecords,
    loadRecords,
    handleAddRecord,
    handleDeleteRecord
  } = useRecord();

  // 使用 useField hook
  const {
    fields, setFields,
    loadFields,
    handleAddField,
    handleDeleteField
  } = useField();

  // 包装 loadRecords 以设置状态
  const loadRecordsWrapper = useCallback(async (sheetId?: string) => {
    try {
      const result = await loadRecords(sheetId);
      setRecords(result);
    } catch (error) {
      console.error("Failed to load records:", error);
    }
  }, [loadRecords, setRecords]);

  // 包装 loadFields 以设置状态
  const loadFieldsWrapper = useCallback(async (sheetId?: string) => {
    try {
      const result = await loadFields(sheetId);
      setFields(result);
    } catch (error) {
      console.error("Failed to load fields:", error);
    }
  }, [loadFields, setFields]);

  const { eventUnsubscribers } = useDocumentEvents(
    loadDocumentInfo,
    loadSheets,
    loadActiveSheet,
    loadFieldsWrapper,
    loadRecordsWrapper,
    activeSheet
  );

  useEffect(() => {
    const initialize = async () => {
      setLoading(true);
      try {
        await Promise.all([
          loadDocumentInfo(),
          loadSheets(),
          loadActiveSheet(),
        ]);
      } catch (error: any) {
        console.error(`${locale.operationFailed}: ${error.message}`);
      } finally {
        setLoading(false);
      }
    };

    initView({
      onReady: async () => {
       
        // 初始化数据
        await initialize();
      },
    });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (loading) {
    return (
      <div className='page'>
        <div className='loading'>
          <Typography.Text>{locale.loading}</Typography.Text>
        </div>
      </div>
    );
  }

  return (
    <div className="app">
      <div className="header">
        {documentInfo && (
          <div>
            <span style={{color: '#1890ff', marginLeft: '8px'}}>[{locale.currentTable}]</span> 
             <Typography.Text strong>{documentInfo && documentInfo.currentSheet}</Typography.Text>
          </div>
        )}
      </div>
      <Tabs defaultActiveKey="1">
         <Tabs.TabPane tab="汇率同步" key="1">
          {/* <FinanceList /> */}
          111
        </Tabs.TabPane>
        <Tabs.TabPane tab="查找重复项" key="2">
          <FindDuplicate />
        </Tabs.TabPane>
      </Tabs>
    </div>
  );
}

export default App;